// 全局变量
let currentConfig = null;
let editingUrlId = null;

// 加载数据
async function loadData() {
    await Promise.all([
        loadLoadBalancingConfig(),
        loadUrls()
    ]);
}

// 加载负载均衡配置
async function loadLoadBalancingConfig() {
    try {
        const data = await apiRequest('/api/admin/load-balancing');
        if (data && data.errcode === 0) {
            currentConfig = data.data;
            
            // 更新统计信息
            const totalUrls = currentConfig.urls.length;
            const activeUrls = currentConfig.urls.filter(u => u.enabled).length;
            
            document.getElementById('totalUrls').textContent = totalUrls;
            document.getElementById('activeUrls').textContent = activeUrls;
            document.getElementById('currentStrategy').textContent = currentConfig.strategy || 'round-robin';
            
            // 更新负载均衡开关
            const lbEnabled = currentConfig.enabled || false;
            document.getElementById('lbEnabled').checked = lbEnabled;
            document.getElementById('lbStatus').textContent = lbEnabled ? '启用' : '禁用';
            
            // 更新策略选择
            updateStrategySelector(currentConfig.strategy || 'round-robin');
        }
    } catch (error) {
        console.error('加载负载均衡配置失败:', error);
        showMessage('加载配置失败', 'error');
    }
}

// 加载 URL 列表
async function loadUrls() {
    try {
        const data = await apiRequest('/api/admin/load-balancing');
        if (data && data.errcode === 0) {
            const urls = data.data.urls || [];
            const tbody = document.getElementById('urlTableBody');
            
            if (urls.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="8" style="text-align: center; padding: 40px; color: var(--text-secondary);">
                            暂无 URL 数据,点击右上角"添加 URL"按钮开始添加
                        </td>
                    </tr>
                `;
            } else {
                tbody.innerHTML = urls.map(url => `
                    <tr>
                        <td>${url.id}</td>
                        <td>${url.name}</td>
                        <td style="font-family: 'Courier New', monospace; font-size: 12px; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${url.url}">${url.url}</td>
                        <td>${url.weight || 1}</td>
                        <td>
                            <span class="badge ${url.enabled ? 'badge-success' : 'badge-error'}">
                                ${url.enabled ? 'ENABLED' : 'DISABLED'}
                            </span>
                        </td>
                        <td>${url.accessCount || 0}</td>
                        <td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${url.description || ''}">${url.description || '-'}</td>
                        <td>
                            <div class="url-actions">
                                <button class="btn btn-primary" onclick="editUrl(${url.id})">编辑</button>
                                <button class="btn btn-error" onclick="deleteUrl(${url.id}, '${url.name}')">删除</button>
                            </div>
                        </td>
                    </tr>
                `).join('');
            }
        }
    } catch (error) {
        console.error('加载 URL 列表失败:', error);
        showMessage('加载 URL 列表失败', 'error');
    }
}

// 更新策略选择器
function updateStrategySelector(strategy) {
    const options = document.querySelectorAll('.strategy-option');
    options.forEach(option => {
        if (option.dataset.strategy === strategy) {
            option.classList.add('active');
        } else {
            option.classList.remove('active');
        }
    });
}

// 策略选择器点击事件
document.addEventListener('DOMContentLoaded', () => {
    const options = document.querySelectorAll('.strategy-option');
    options.forEach(option => {
        option.addEventListener('click', async () => {
            const strategy = option.dataset.strategy;
            await updateStrategy(strategy);
        });
    });
});

// 更新策略
async function updateStrategy(strategy) {
    try {
        const data = await apiRequest('/api/admin/load-balancing/strategy', {
            method: 'POST',
            body: JSON.stringify({ strategy })
        });
        
        if (data && data.errcode === 0) {
            showMessage('策略更新成功!', 'success');
            updateStrategySelector(strategy);
            document.getElementById('currentStrategy').textContent = strategy;
        } else {
            showMessage(data.message || '更新失败', 'error');
        }
    } catch (error) {
        console.error('更新策略失败:', error);
        showMessage('更新策略失败', 'error');
    }
}

// 切换负载均衡
async function toggleLoadBalancing() {
    const enabled = document.getElementById('lbEnabled').checked;
    
    try {
        const data = await apiRequest('/api/admin/load-balancing/strategy', {
            method: 'POST',
            body: JSON.stringify({ enabled })
        });
        
        if (data && data.errcode === 0) {
            showMessage(enabled ? '负载均衡已启用' : '负载均衡已禁用', 'success');
            document.getElementById('lbStatus').textContent = enabled ? '启用' : '禁用';
        } else {
            showMessage(data.message || '操作失败', 'error');
            // 恢复开关状态
            document.getElementById('lbEnabled').checked = !enabled;
        }
    } catch (error) {
        console.error('切换负载均衡失败:', error);
        showMessage('操作失败', 'error');
        document.getElementById('lbEnabled').checked = !enabled;
    }
}

// 显示添加模态框
function showAddModal() {
    editingUrlId = null;
    document.getElementById('modalTitle').textContent = '添加 URL';
    document.getElementById('urlForm').reset();
    document.getElementById('urlId').value = '';
    document.getElementById('urlEnabled').checked = true;
    document.getElementById('urlWeight').value = 1;
    document.getElementById('submitText').textContent = '保存';
    document.getElementById('urlModal').classList.add('active');
}

// 编辑 URL
async function editUrl(id) {
    editingUrlId = id;
    const url = currentConfig.urls.find(u => u.id === id);
    
    if (!url) {
        showMessage('URL 不存在', 'error');
        return;
    }
    
    document.getElementById('modalTitle').textContent = '编辑 URL';
    document.getElementById('urlId').value = url.id;
    document.getElementById('urlName').value = url.name;
    document.getElementById('urlAddress').value = url.url;
    document.getElementById('urlWeight').value = url.weight || 1;
    document.getElementById('urlDescription').value = url.description || '';
    document.getElementById('urlEnabled').checked = url.enabled;
    document.getElementById('submitText').textContent = '更新';
    document.getElementById('urlModal').classList.add('active');
}

// 关闭模态框
function closeModal() {
    document.getElementById('urlModal').classList.remove('active');
    editingUrlId = null;
}

// 表单提交
document.getElementById('urlForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const submitBtn = document.querySelector('#urlForm button[type="submit"]');
    const submitText = document.getElementById('submitText');
    const originalText = submitText.textContent;
    
    submitBtn.disabled = true;
    submitText.innerHTML = '<span class="loading"></span> 保存中...';
    
    try {
        const formData = {
            name: document.getElementById('urlName').value.trim(),
            url: document.getElementById('urlAddress').value.trim(),
            weight: parseInt(document.getElementById('urlWeight').value) || 1,
            description: document.getElementById('urlDescription').value.trim(),
            enabled: document.getElementById('urlEnabled').checked
        };
        
        let data;
        if (editingUrlId) {
            // 更新
            data = await apiRequest(`/api/admin/urls/${editingUrlId}`, {
                method: 'PUT',
                body: JSON.stringify(formData)
            });
        } else {
            // 添加
            data = await apiRequest('/api/admin/urls', {
                method: 'POST',
                body: JSON.stringify(formData)
            });
        }
        
        if (data && data.errcode === 0) {
            showMessage(editingUrlId ? 'URL 更新成功!' : 'URL 添加成功!', 'success');
            closeModal();
            loadData();
        } else {
            showMessage(data.message || '操作失败', 'error');
        }
    } catch (error) {
        console.error('保存 URL 失败:', error);
        showMessage('保存失败,请检查网络连接', 'error');
    } finally {
        submitBtn.disabled = false;
        submitText.textContent = originalText;
    }
});

// 删除 URL
async function deleteUrl(id, name) {
    if (!confirm(`确定要删除 "${name}" 吗?`)) {
        return;
    }
    
    try {
        const data = await apiRequest(`/api/admin/urls/${id}`, {
            method: 'DELETE'
        });
        
        if (data && data.errcode === 0) {
            showMessage('URL 删除成功!', 'success');
            loadData();
        } else {
            showMessage(data.message || '删除失败', 'error');
        }
    } catch (error) {
        console.error('删除 URL 失败:', error);
        showMessage('删除失败', 'error');
    }
}

// 页面加载时执行
window.addEventListener('load', () => {
    loadData();
});

// 点击模态框外部关闭
document.getElementById('urlModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeModal();
    }
});

